import { store } from "@/store";
import { defineStore } from 'pinia'
import { getDicts as getDicts } from '@/api/data';

export const useDictStore = defineStore('pinia-dict', {
  state: ():any=> ({ 
    dict: new Array(),
  }),

  actions: {

    SET_DICT({ key, value }:any) {
      if (key !== null && key !== '') {
        this.dict.push({
          key: key,
          value: value,
        });
      }
    },
    REMOVE_DICT(key: string) {
      try {
        for (let i = 0; i < this.dict.length; i++) {
          if (this.dict[i].key == key) {
            this.dict.splice(i, 1);
            return true;
          }
        }
      } catch (e) {}
    },

    CLEAN_DICT(){
      this.dict = new Array();
    },

    
    // 设置字典
    setDict(data:any) {
      this.SET_DICT( data);
    },
    // 删除字典
    removeDict(data:any) {
      this.REMOVE_DICT( data);
    },
    
    // 清空字典
    cleanDict(data:any) {
      this.CLEAN_DICT( data);
    },
    
    // 获取字典
    loadDict(dictType:string){
      const storeDict = searchDictByKey(this.dict, dictType);
          if (storeDict) {
            return new Promise((resolve) => {
              resolve(storeDict);
            });
          } else {
            return new Promise((resolve, reject) => {
              getDicts(dictType)
                .then((res) => {
                  this.setDict({ key: dictType, value: res });
                  resolve(res);
                })
                .catch((error) => {
                  reject(error);
                });
            });
          }
    }
   
  },
})

function searchDictByKey(dict:any[], key:string) {
  if (key == null && key == '') {
    return null;
  }
  try {
    for (let i = 0; i < dict.length; i++) {
      if (dict[i].key == key) {
        return dict[i].value;
      }
    }
  } catch (e) {
    return null;
  }
}

export function useDictStoreHook() {
  return useDictStore(store);
}
